import { Injectable } from '@nestjs/common';
import { CreateSpiderDto } from './dto/create-spider.dto';
import { UpdateSpiderDto } from './dto/update-spider.dto';
import axios from 'axios';
import * as cheerio from 'cheerio';
import * as fs from 'fs';
import * as path from 'path';

@Injectable()
export class SpiderService {
  create(createSpiderDto: CreateSpiderDto) {
    return 'This action adds a new spider';
  }

  async findAll() {
    const urls:string[] = [];
    const baseUrl =  "https:";
    const nextText = "下一页";
    let index = 0;
    const getCosplay = async () => {
      console.log(index);
      const body = await axios
        .get(`https://www.tukuppt.com/speciall/meizi0473${index ? '_' + index : ""}.html`)
        .then(async res=>res.data);

      const $ = cheerio.load(body);  

      const page = $(".page").find("a");
      const pageArray = page.map((index,item)=>{
        return $(item).text();
      }).toArray();
      if(pageArray.includes(nextText)){
        $("img.s-pic").each(function(){
          urls.push(baseUrl + $(this).attr("data-original"));
        }); 
        index++;
        await getCosplay();
      }

    };
    await getCosplay();
    this.writeFile(urls);
    // console.log(urls);
    return `cos`;
  }

  writeFile(urls:string[]){
     urls.forEach(async url=>{
      const buffer = await axios.get(url,{responseType:"arraybuffer"}).then(res=>res.data);
      const ws = fs.createWriteStream(path.join(__dirname,"../cosplay" + new Date().getTime() + '.jpg'));
      ws.write(buffer);
     });
  }

  findOne(id: number) {
    return `This action returns a #${id} spider`;
  }

  update(id: number, updateSpiderDto: UpdateSpiderDto) {
    return `This action updates a #${id} spider`;
  }

  remove(id: number) {
    return `This action removes a #${id} spider`;
  }
}
